package jwebtester.dal.provider.impl;

import infrastructure.Scopes;

import java.util.ArrayList;
import java.util.List;

import jwebtester.business.services.MapperService;
import jwebtester.dal.entities.UserEntity;
import jwebtester.dal.provider.UserManagementDataProvider;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import utils.CollectionUtils;
import domain.entities.User;

@Repository
@Scope(value = Scopes.Request, proxyMode = ScopedProxyMode.INTERFACES)
public class UserManagementDataProviderImpl implements UserManagementDataProvider {

	private static final Logger LOG = LoggerFactory.getLogger(UserManagementDataProviderImpl.class);
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	private MapperService mapperService;
	
	@Override
	@Transactional
	public List<User> getUsers(int organizationID) {
		Session session = sessionFactory.getCurrentSession();

		try{
			final List<User> result = new ArrayList<User>();

			final Query query = session.createQuery("from UserEntity u where u.organizationEntity.id = :orgID");
			query.setInteger("orgID", organizationID);

			List<UserEntity> dataEntities = CollectionUtils.castList( query.list());
			if (dataEntities != null && dataEntities.size() > 0){
				for(UserEntity dataEntity : dataEntities){
					User user = (User)mapperService.mapTo(dataEntity, User.class);
					result.add(user);
				}
			}
			
			return result;
		}
		catch(RuntimeException ex){
			LOG.error(String.format("Error loading users. Organization ID=%s", organizationID));
			throw ex;
		}
	}

}
